#include "pch.h"
#include "Helper.h"
#include "DXContext.h"
#include <Strsafe.h>
#include <sstream>
#include <ostream>

using namespace DXBase;
using namespace Microsoft::WRL;
using namespace Windows::Storage;

#ifdef _DEBUG
volatile LONG DebugObject::count = 0;
DebugObject::~DebugObject()
{
	std::wostringstream ss;
	ss << L"~" << name.c_str() << L"(" << id << L")\r\n";
	OutputDebugString(ss.str().c_str());
}
DebugObject::DebugObject(const wchar_t *text)
	: name(text)
{
	id = InterlockedIncrement(&count);
	std::wostringstream ss;
	ss << name.c_str() << L"(" << id << L")\r\n";
	OutputDebugString(ss.str().c_str());
}
#endif

void DXBase::RegisterPropertyChangedSafely(
	Windows::UI::Xaml::Data::INotifyPropertyChanged^ src, 
	Windows::UI::Xaml::Data::PropertyChangedEventHandler^ handler, 
	Windows::Foundation::EventRegistrationToken& token)
{
	auto w = Windows::UI::Core::CoreWindow::GetForCurrentThread();
	if (!w)
		return;
	if (w->Dispatcher->HasThreadAccess) {
		token = src->PropertyChanged += handler;
	}
	else {
		w->Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Low, 
			ref new Windows::UI::Core::DispatchedHandler([src, handler, &token]() -> void
			{
				DXBase::RegisterPropertyChangedSafely(src, handler, token);
			})
		);
	}
}


Platform::String^ DXBase::GetFileExtension(_In_ Platform::String^ filename)
{
    int lastDotIndex = -1;
    for (int i = filename->Length() - 1; i >= 0 && lastDotIndex == -1; i--)
    {
        if (*(filename->Data() + i) == '.')
        {
            lastDotIndex = i;
        }
    }
    if (lastDotIndex != -1)
    {
        std::unique_ptr<wchar_t[]> extension(new wchar_t[filename->Length() - lastDotIndex]);
        for (unsigned int i = 0; i < filename->Length() - lastDotIndex; i++)
        {
            extension[i] = tolower(*(filename->Data() + lastDotIndex + 1 + i));
        }
        return ref new Platform::String(extension.get());
    }
    return "";
}
